import React, { useState, useEffect, useRef } from 'react';
import "./UserRegulate.scss"
import { Button, Input, Radio, Space, Table, Switch, ConfigProvider, notification, Drawer, Form, Spin, Modal } from "antd"
import { DeleteFilled, SyncOutlined, FullscreenOutlined, EditOutlined, FileSearchOutlined, PlusOutlined, DeleteOutlined } from "@ant-design/icons"
import zhCN from 'antd/locale/zh_CN';
import * as service from "../../../../api"
import _ from "lodash"



let { Search } = Input

const UserRegulate = () => {
    // 国际化中文
    const [locale] = useState(zhCN);
    // 表格加载请求加载时的加载效果
    let [loading, setLoading] = useState(false)
    // 表格渲染数据
    let [data, setData] = useState([])
    // 抽屉的开关控制
    let [open, setopen] = useState(false)
    // 用来判断新增还是修改的抽屉表单信息
    let [addusermessage, setaddusermessage] = useState({
        userId: ''
    })
    // 抽屉表单组件实例
    let [form] = Form.useForm()
    // 当前页
    let [page, setPage] = useState(1)
    // 每页显示条数
    let [sizepage, setSizepage] = useState(4)
    let [alltotal, setalltotal] = useState()
    let [image, setimage] = useState("")
    let [onload, setonload] = useState(false)
    let [modalopen, setmodalopen] = useState(false)
    let [delid, setdelid] = useState('')
    let myimage = useRef(null)
    let user_queryAll = async () => {
        setLoading(true)
        let res = await service.default.kxd.user_queryAll({ cp: page, ps: sizepage })
        // console.log("默认参数分页请求", res);
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
            setalltotal(res.data.count)
        }
    }
    useEffect(() => {
        user_queryAll()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    let onSearch = async (value: string) => {
        setLoading(true)
        console.log("获取输入框的值：", value);
        let res = await service.default.kxd.user_queryKey({ key: value })
        console.log(res);
        if (res.data.code === 200) {
            setLoading(false)
            setalltotal(res.data.count)
            setData(res.data.data)
        } else if (res.data.code === 500) {
            notification.error({ message: "没有改用户名或账户" })
        }
    }
    let [statubtns] = useState([
        { label: '全部', value: '全部' },
        { label: '启动', value: '启动' },
        { label: '禁用', value: '禁用' },
    ])
    let renderstatus = async (e: any) => {
        // console.log("点击了：", e.target.value);
        if (e.target.value === "全部") {
            // console.log("点击了全部");
            user_queryAll()
        } else if (e.target.value === "启动") {
            // console.log("点击了启动");
            setLoading(true)
            let res = await service.default.kxd.user_queryStatus({ status: 0 })
            if (res.data.code === 200) {
                console.log(res.data.data);
                setLoading(false)
                setData(res.data.data)
                setalltotal(res.data.data.length)
            }
        } else if (e.target.value === "禁用") {
            console.log("点击了禁用");
            setLoading(true)
            let res = await service.default.kxd.user_queryStatus({ status: 1 })
            if (res.data.code === 200) {
                console.log(res.data.data);
                setLoading(false)
                setData(res.data.data)
                setalltotal(res.data.data.length)
            }
        }
    }
    let switchstatus = async (status: any, userId: any) => {
        console.log(status, userId);
        if (status === 0) {
            status = 1
            let res = await service.default.kxd.user_updateStatus(userId, status)
            if (res.data.code === 200) {
                notification.success({ message: "状态更改成功" })
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var newData: any = _.cloneDeep(data)
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var item: any = newData.find((item: any) => item.userId === userId)
                if (item) {
                    item.status = status
                }
                setData(newData)
            }
        } else if (status === 1) {
            status = 0
            let res = await service.default.kxd.user_updateStatus(userId, status)
            if (res.data.code === 200) {
                notification.success({ message: "状态更改成功" })
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var newData: any = _.cloneDeep(data)
                // eslint-disable-next-line @typescript-eslint/no-redeclare
                var item: any = newData.find((item: any) => item.userId === userId)
                if (item) {
                    item.status = status
                }
                setData(newData)
            }
        }

    }
    // 打开抽屉
    let useradd = () => {
        setopen(true)
    }
    const columns: any = [
        {
            title: '序号',
            key: 'serialnumber',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    {index + 1}
                </Space>
            ),
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '账户',
            dataIndex: 'userAccount',
            key: 'userAccount',
        },
        {
            title: '手机号',
            key: 'userPhone',
            dataIndex: 'userPhone'
        },
        {
            title: '状态',
            key: 'status',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    <Switch
                        checkedChildren="启动"
                        unCheckedChildren="禁用"
                        checked={record.status === 0 ? true : false}
                        onChange={() => { switchstatus(record.status, record.userId) }} />
                </Space>
            )
        },
        {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime'
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: any, index: any) => (
                <Space size="middle">
                    <Button><FileSearchOutlined /></Button>
                    <Button onClick={() => { onedit(record) }}><EditOutlined /></Button>
                    <Button onClick={() => { ondel(record) }}><DeleteOutlined /></Button>
                </Space>
            ),
        },
    ];
    // 关闭抽屉
    let onClose = () => {
        setopen(false)
        form.setFieldsValue({
            password: "",
            userAccount: "",
            userName: "",
            userPhone: "",
        })
        setaddusermessage({
            userId: ''
        })
        setimage("")
    }
    // 添加并且表单验证成功后的回调函数
    let onFinish = async (values: any) => {
        console.log(values);
        if (addusermessage.userId) {
            console.log("修改");
            let res = await service.default.kxd.user_querySingle({ userId: addusermessage.userId })
            console.log("请求单个数据", res);
            let newset = res.data.data
            Object.assign(newset, values, { userAvatar: image })

            let setregulate = await service.default.kxd.user_update(newset)
            console.log("修改请求", setregulate);
            if (setregulate.data.code === 200) {
                onClose()
                notification.success({ message: "修改成功" })
                user_queryAll()
            }
        } else {
            Object.assign(values, {
                status: 0,
                createTime: new Date().toLocaleString().replace(/\//g, "-"),
                userAvatar: image
            })
            // console.log(values);
            let res = await service.default.kxd.user_add(values)
            console.log("添加请求结果", res);
            if (res.data.code === 200) {
                onClose()
                notification.success({ message: "新增成功" })
                user_queryAll()
            } else if (res.data.code === 500) {
                onClose()
                notification.success({ message: "该用户已存在" })
            }
        }
    }
    // 点击编辑按钮
    let onedit = async (record: any) => {
        // let res = await service.default.kxd.user_querySingle({ userId: userId })
        // console.log("请求单个数据", res);
        // if (res.data.code === 200) {
        console.log(record);

        useradd()
        form.setFieldsValue(record)
        setaddusermessage(record)
        setimage(record.userAvatar)
        // console.log("存储单个信息", addusermessage);
        // }
    }
    // 点击每项删除
    let ondel = async (record: any) => {
        let res = await service.default.kxd.user_delete(record.userId)
        if (res.data.code === 200) {
            onClose()
            notification.success({ message: "删除成功" })
            user_queryAll()
        }
    }
    // const showModal = (record: any) => {
    //     setmodalopen(true);
    //     setdelid(record.userId)
    // };

    const handleOk = async () => {
        setmodalopen(false);
        let res = await service.default.kxd.user_delete(delid)
        if (res.data.code === 200) {
            onClose()
            notification.success({ message: "删除成功" })
            user_queryAll()
            setdelid("")
        }
    };

    const handleCancel = () => {
        setmodalopen(false);
        setdelid("")
    };
    // 每页显示数据条数改变时显示的回调函数
    let pagechange = async (current: any, size: any) => {
        console.log("current:", current, "size:", size);
        setSizepage(size)
        setLoading(true)
        let res = await service.default.kxd.user_queryAll({ cp: current, ps: size })
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
        }
    }
    // 当前页改变时的回调函数
    let onChange = async (page: any, pageSize: any) => {
        console.log("page:", page, "pageSize:", pageSize);
        setPage(page)
        setLoading(true)
        let res = await service.default.kxd.user_queryAll({ cp: page, ps: pageSize })
        if (res.data.code === 200) {
            setLoading(false)
            setData(res.data.data.data)
        }
    }

    // 
    let upimage = () => {
        // console.log(myimage.current);
        let im: any = myimage.current
        im.click()
    }
    let getimage = async (e: any) => {
        setonload(true)
        let file = e.target.files[0]
        console.log("文件：", file);
        const formData: any = new FormData();
        formData.append('file', file);
        console.log("文件存储", formData);
        let res = await service.default.kxd.user_uploade(formData)
        console.log(res);
        if (res.data.code === 200) {
            setimage(res.data.data)
            setonload(false)
            notification.success({ message: "上传成功" })
        }
    }
    // let yalidateCustomRule = () => {
    //     if (image === "") {
    //         return Promise.resolve("请上传图片")
    //     }
    //     return Promise.reject()
    // }
    return (
        <div className='userregulate_box'>
            <div className="function_box">
                <div className="addbtn_box">
                    <Button type="primary" onClick={useradd}>新增用户</Button>
                </div>
                <div className="btns_box">
                    <div className="status_box" >
                        <Radio.Group
                            options={statubtns}
                            onChange={renderstatus}
                            optionType="button"
                            defaultValue="全部"
                        />
                    </div>
                    <div className="search_box">
                        <Search
                            placeholder="请输入用户名、账号关键字"
                            allowClear
                            enterButton="搜索"
                            size="middle"
                            onSearch={onSearch}
                        />
                    </div>
                    <div className="iocnbtns">
                        <div className="del">
                            <DeleteFilled />
                        </div>
                        <div className="reset">
                            <SyncOutlined />
                        </div>
                        <div className="fullscreen">
                            <FullscreenOutlined />
                        </div>
                    </div>
                </div>
            </div>
            <div className="table_box">
                <ConfigProvider locale={locale}>
                    <Table
                        columns={columns}
                        dataSource={data}
                        size="middle"
                        loading={loading}
                        pagination={
                            {
                                position: ["bottomCenter"],
                                pageSize: sizepage, // 每页显示数据条数
                                current: page, // 当前页
                                showQuickJumper: true, //快速跳转
                                total: alltotal, // 所有条数
                                showTotal: (total: any) => `共 ${total} 条数据`,
                                pageSizeOptions: [2, 4, 6, 8, 10],
                                onShowSizeChange: pagechange,
                                onChange: onChange,
                                showSizeChanger: true
                            }
                        }
                    />
                </ConfigProvider>
            </div>
            <Drawer title={addusermessage.userId ? "修改用户" : "新增用户"} placement="right" onClose={onClose} open={open}>
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    onFinish={onFinish}
                    form={form}
                >
                    <Form.Item
                        label="用户名"
                        name="userName"
                        rules={[{ required: true, message: '请输入新建的用户名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="账户"
                        name="userAccount"
                        rules={[{ required: true, message: '请输入新建的用户名' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="手机号"
                        name="userPhone"
                        rules={[{ required: true, message: '请输入新建的用户名' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入新建密码' }]}
                    >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item
                        label="上传头像"
                        name="image"
                    >
                        {/* rules={[{ validator: yalidateCustomRule }]} */}
                        <input type="file" accept="image/*" style={{ display: 'none' }} name="userAvatar" ref={myimage} onChange={getimage} />
                        <div className="image_box" onClick={upimage}>
                            {
                                onload ?
                                    <Spin />
                                    :
                                    <>
                                        <PlusOutlined />
                                        <img className={image ? "img_on" : ""} src={image} alt="" />
                                    </>
                            }
                        </div>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            {addusermessage.userId ? "修改用户" : "新增用户"}
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
            <Modal open={modalopen} onOk={handleOk} onCancel={handleCancel}>
                <p>确认要删除吗</p>
            </Modal>
        </div>
    );
};

export default UserRegulate;